/*
 * @Author: pardon110
 * @Date: 2024-03-16 11:19:49
 * @LastEditors: pardon110@qq.com
 * @LastEditTime: 2024-03-16 11:48:13
 * @FilePath: \days7\web\base\gee\gee.go
 * @Description:
 */
package gee

import (
	"fmt"
	"log"
	"net/http"
)

type HandlerFunc func(w http.ResponseWriter, r *http.Request)

// Engine implements the interface of ServeHTTP
type Engine struct {
	// http.verrb : handle http
	router map[string]HandlerFunc
}

func New() *Engine {
	return &Engine{router: make(map[string]HandlerFunc)}
}

// 路由注册
func (e *Engine) addRoute(method string, pattern string, handler HandlerFunc) {
	key := method + "-" + pattern
	log.Printf("Add Route: %4s - %s", method, pattern)
	e.router[key] = handler
}

func (e *Engine) GET(pattern string, handler HandlerFunc) {
	e.addRoute("GET", pattern, handler)
}

func (e *Engine) POST(pattern string, handler HandlerFunc) {
	e.addRoute("POST", pattern, handler)
}

// 路由匹配
func (e *Engine) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	key := r.Method + "-" + r.URL.Path
	if process, ok := e.router[key]; ok {
		process(w, r)
	} else {
		fmt.Fprintf(w, http.StatusText(http.StatusNotFound)+": %s\n", r.URL)
	}
}

func (e *Engine) Run(addr string) (err error) {
	return http.ListenAndServe(addr, e)
}
